package com.ztx.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ztx.service.PermissionService;
import com.ztx.utils.CommonResult;
import com.ztx.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    PermissionService permissionService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization").substring(7);

        if (!StringUtils.hasLength(token)) {
            CommonResult result = CommonResult.error(0, "未登录");
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().write(json);
            return false;
        }

        try{
            jwtTokenUtil.validateToken(token);
        } catch (Exception e){
            CommonResult result = CommonResult.error(0, "未登录");
            String json = JSONObject.toJSONString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().write(json);
            return false;
        }

        
        // 检查是否有用户权限
        Long userId = jwtTokenUtil.getUserIdFromToken(token);
        List<String> modules = permissionService.getModuleByUserId(userId);

        String requestURI = request.getRequestURI();
        log.info(requestURI);

        // todo 权限校验


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
